package com.hertz.alarm.util;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;

import org.apache.http.HttpResponse;
import org.apache.http.HttpStatus;
import org.apache.http.NameValuePair;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.client.utils.URLEncodedUtils;
import org.apache.http.conn.params.ConnManagerParams;
import org.apache.http.conn.params.ConnPerRouteBean;
import org.apache.http.conn.scheme.PlainSocketFactory;
import org.apache.http.conn.scheme.Scheme;
import org.apache.http.conn.scheme.SchemeRegistry;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.impl.conn.tsccm.ThreadSafeClientConnManager;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.params.BasicHttpParams;
import org.apache.http.params.HttpParams;
import org.apache.http.util.EntityUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

public class HttpClientUtil {

    public static final String UTF_8 = "UTF-8";

    public static final String GBK = "GBK";

    private static DefaultHttpClient httpclient;

    private static final Logger log = LoggerFactory.getLogger(HttpClientUtil.class);



    static {
        HttpParams params = new BasicHttpParams();
        params.setParameter("http.connection.timeout", 5000);
        params.setParameter("http.socket.timeout", 5000);
        params.setParameter("http.conn-manager.timeout", 6000L);
        params.setParameter("http.conn-manager.max-total", 200);
        ConnPerRouteBean connPerRoute = new ConnPerRouteBean(100); 
        ConnManagerParams.setMaxConnectionsPerRoute(params,connPerRoute);  
//        params.setParameter("http.conn-manager.max-per-route", 100);
        params.setParameter("http.protocol.element-charset", UTF_8);
        params.setParameter("http.protocol.content-charset", UTF_8);
        

        SchemeRegistry registry = new SchemeRegistry();
        registry.register(new Scheme("http", PlainSocketFactory.getSocketFactory(), 80));
        ThreadSafeClientConnManager manager = new ThreadSafeClientConnManager(params, registry);
        httpclient = new DefaultHttpClient(manager, params);
    }



    public static String getByEncode(String uri,Map<String,String> headers, String responseEncode) throws IOException {
        HttpGet httpGet = new HttpGet(uri);
        if(headers != null && !headers.isEmpty()){
	        for(Entry<String, String> entry:headers.entrySet()){
	        	httpGet.setHeader(entry.getKey(),entry.getValue());  	
	        }
        }
        //httpGet.setHeader("Cookie","CUCTV_login_uid=2");
        HttpResponse httpResponse = httpclient.execute(httpGet);

        
        String charset = responseEncode == null ||  "".equals(responseEncode) ? EntityUtils.getContentCharSet(httpResponse.getEntity()) : responseEncode;
        //log.debug("url  responseEncode:{}",responseEncode,+":"+charset+":"+uri);
        String s = EntityUtils.toString(httpResponse.getEntity(), charset);
        log.debug("url:{},result:", uri, s);
        return s;
    }

    
    public static String get(String url, Map<String, String> params) throws IOException {
   	 return getByEncode(addParams(url, params, "UTF-8"),null, "UTF-8");
    }

    public static String get(String url, Map<String, String> params,Map<String,String> headers) throws IOException {
    	 return getByEncode(addParams(url, params, "UTF-8"),headers, "UTF-8");
    }

    public static String get(String url, Map<String, String> params, String encode, String responseEncode) throws IOException {
        return getByEncode(addParams(url, params, encode),null,responseEncode);
    }



    public static String post(String uri, Map<String, String> m, String encoding) throws IOException {
        UrlEncodedFormEntity entity = new UrlEncodedFormEntity(getParamList(m), encoding);
        log.debug("post: {}{}", uri, EntityUtils.toString(entity));
        HttpPost httpPost = new HttpPost(uri);
        httpPost.setEntity(entity);
        HttpResponse httpResponse = httpclient.execute(httpPost);
        String charset = encoding == null ? EntityUtils.getContentCharSet(httpResponse.getEntity()) : encoding;
        if (httpResponse.getStatusLine().getStatusCode() == HttpStatus.SC_OK) {
            return EntityUtils.toString(httpResponse.getEntity(), charset);
        } else {
            httpPost.abort();
            return null;
        }
    }



    public static List<NameValuePair> getParamList(Map<String, String> params) {
        List<NameValuePair> qparams = new ArrayList<NameValuePair>();
        if(params == null ) return qparams;
        for (Map.Entry<String, String> entry : params.entrySet()) {
            qparams.add(new BasicNameValuePair(entry.getKey(), entry.getValue()));
        }
        return qparams;
    }



    public static String addParams(String baseURI, Map<String, String> params, String encode) {
        if (baseURI == null) return null;
        String paramStr = URLEncodedUtils.format(getParamList(params), encode);
        char sp = (baseURI.indexOf('?') != -1) ? '&' : '?';
        return baseURI + sp + paramStr;
    }
    
    public static void main(String argv[]){
    		
    }
}
